import type {DailySuggestItem} from "@/types/home";
import {useIndexListHeightStore} from "@/stores/indexListHeight";

/**
 *  洗牌算法来随机排序数组。
 * @param array
 */
export async function shuffleArray(array: any[]): Promise<any[]> {
    const heightStore = useIndexListHeightStore()
    const {windowWidth} = uni.getSystemInfoSync()
    const w = (windowWidth - 30) / 2
    let arr_1: DailySuggestItem[] = []
    let arr_2: DailySuggestItem[] = []
    let i = 1
    await new Promise((resolve, reject) => {
        for (const arr of array) {
            uni.getImageInfo({
                src: arr.img,
                success: function (res) {
                    const height = w / res.width * res.height
                    // 判断高度
                    if (heightStore.listHeight_1 <= heightStore.listHeight_2) {
                        // 添加进入list1
                        arr_1.push({...arr, h: height, list: 1})
                        heightStore.listHeight_1 += height
                    } else {
                        arr_2.push({...arr, h: height, list: 2})
                        heightStore.listHeight_2 += height
                    }
                },
                complete: () => {
                    i++
                    if (i >= array.length) {
                        resolve(true)
                    }
                }
            })
        }
    })
    return [...arr_1, ...arr_2]
}